package top.knos.od.support;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.thymeleaf.util.StringUtils;
import top.knos.od.vo.PagePathsVo;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class StaticPagePathFinder {
    private final ResourcePatternResolver resourceResolver;

    public StaticPagePathFinder(ResourcePatternResolver resourceResolver) {
        this.resourceResolver = resourceResolver;
    }

    public List<PagePathsVo> findPaths() throws IOException {
        Resource baseResource = resourceResolver.getResource("classpath:/templates/pages");
        String basePath = baseResource.getURL().getPath();
        Resource[] resources = resourceResolver.getResources("classpath:/templates/pages/**/*.html");
        List<PagePathsVo> paths = new ArrayList<>();
        for (Resource resource : resources) {
            String filePath = relativeFilePath(basePath, resource);
            paths.add(new PagePathsVo(filePath, buildRequestMapping(filePath)));
        }
        return paths;
    }

    private String relativeFilePath(String basePath, Resource resource) throws IOException {
        return resource.getURL().getPath().substring(basePath.length()).replace(".html", "");
    }

    private String buildRequestMapping(String filePath) {
        var requestMapping = filePath;
        if (requestMapping.endsWith("/index")) {
            requestMapping = requestMapping.replace("/index", "");
            if (StringUtils.isEmpty(requestMapping)) {
                requestMapping = "/";
            }
        }
        return requestMapping;
    }
}
